// import React, { useState } from 'react';
// import '../../style/zhanghu.css';

// const ProfileModal = ({ onClose, isVisible }) => {
//   const [isEditing, setIsEditing] = useState(false);
//   const [avatar, setAvatar] = useState('src/img/avatar.jpg');
//   const [nickname, setNickname] = useState('Denselin');
//   const [gender, setGender] = useState('男');
//   const [signature, setSignature] = useState('爱听音乐');
//   const [birthday, setBirthday] = useState('1990-01-01');

//   const handleEdit = () => {
//     setIsEditing(true);
//   };

//   const handleSave = () => {
//     setIsEditing(false);
//   };

//   const handleCancel = () => {
//     setIsEditing(false);
//   };

//   const handleAvatarChange = (e) => {
//     const file = e.target.files[0];
//     if (file) {
//       setAvatar(URL.createObjectURL(file));
//     }
//   };

//   return (
//     <div
//       className={`profile-modal-overlay ${isVisible ? 'profile-modal-show' : ''}`}
//       onClick={onClose}
//     >
//       <div className="profile-modal" onClick={(e) => e.stopPropagation()}>
//         {isEditing ? (
//           <>
//             <img
//               src={avatar}
//               alt="avatar"
//               className="profile-avatar"
//               onClick={() => document.getElementById('avatarInput').click()}
//               style={{ cursor: 'pointer' }}
//             />
//             <input
//               type="file"
//               id="avatarInput"
//               accept="image/*"
//               onChange={handleAvatarChange}
//               style={{ display: 'none' }}
//             />
//             <input
//               type="text"
//               value={nickname}
//               onChange={(e) => setNickname(e.target.value)}
//               className="profile-input"
//               placeholder="昵称"
//             />
//             <input
//               type="text"
//               value={gender}
//               onChange={(e) => setGender(e.target.value)}
//               className="profile-input"
//               placeholder="性别"
//             />
//             <input
//               type="text"
//               value={signature}
//               onChange={(e) => setSignature(e.target.value)}
//               className="profile-input"
//               placeholder="个性签名"
//             />
//             <input
//               type="date"
//               value={birthday}
//               onChange={(e) => setBirthday(e.target.value)}
//               className="profile-input"
//               placeholder="生日"
//             />
//             <div className="profile-btn-group">
//               <button className="profile-btn" onClick={handleSave}>
//                 保存
//               </button>
//               <button className="profile-btn" onClick={handleCancel}>
//                 取消
//               </button>
//             </div>
//           </>
//         ) : (
//           <>
//             <img src={avatar} alt="avatar" className="profile-avatar" />
//             <p className="profile-text">昵称：{nickname}</p>
//             <p className="profile-text">性别：{gender}</p>
//             <p className="profile-text">个性签名：{signature}</p>
//             <p className="profile-text">生日：{birthday}</p>
//             <button className="profile-btn" onClick={handleEdit}>
//               编辑个人信息
//             </button>
//           </>
//         )}
//       </div>
//     </div>
//   );
// };

// export default ProfileModal;



import React, { useState, useEffect } from 'react';
import axios from '../../API'; // 用于发送HTTP请求
import '../../style/zhanghu.css';

const ProfileModal = ({ onClose, isVisible, userId, userNickname }) => {
  const [isEditing, setIsEditing] = useState(false);
  const [avatar, setAvatar] = useState('src/img/avatar.jpg');
  const [nickname, setNickname] = useState(userNickname);
  const [gender, setGender] = useState('');
  const [signature, setSignature] = useState('');
  const [birthday, setBirthday] = useState('');

  useEffect(() => {
    if (userId && isVisible) {

      // 从后端获取用户信息
      axios.get(`/api/user/info/${userId}`)
        .then(response => {
          const userInfo = response.data;
          setAvatar(userInfo.avatar || url);
          setNickname(userInfo.nickname);
          setGender(userInfo.gender);
          setSignature(userInfo.signature);
          setBirthday(userInfo.birthday || avatar );
        })
        .catch(error => {
          console.error("Error fetching user info:", error);
        });
    }
  }, [userId, isVisible]);

  const handleEdit = () => {
    setIsEditing(true);
  };
  const handleCancel = () => {
    setIsEditing(false);
  };

  const handleAvatarChange = (e) => {
    const file = e.target.files[0];
    if (file) {
      // 使用 FormData 构造上传文件的数据
      const formData = new FormData();
      formData.append("file", file); // "file" 是后端接收的文件字段名
  
      // 发送文件上传请求到后端
      axios
        .post(`/api/user/uploadAvatar`, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((response) => {
          // 假设后端返回的 URL 是 `response.data.url`
          const uploadedUrl = response.data.url;
          setAvatar(uploadedUrl); // 更新头像预览
          alert("头像上传成功！");
        })
        .catch((error) => {
          console.error("上传头像失败：", error);
          alert("头像上传失败，请稍后重试！");
        });
    }
  };
  const handleSave = () => {
    const updatedInfo = {
      infoId: userId,
      nickname,
      gender,
      signature,
      birthday,
      avatar
    };
    console.log(updatedInfo);

    // 发送更新请求到后端
    axios.put(`/api/user/info/${userId}`, updatedInfo)
  

      .then(response => {
        alert('个人信息更新成功！');
        setIsEditing(false);  // 关闭编辑模式
      })
      .catch(error => {
        alert('更新失败，请稍后重试！');
        console.error('Error updating user info:', error);
      });
  };

  return (

    <div
      className={`profile-modal-overlay ${isVisible ? 'profile-modal-show' : ''}`}
      onClick={onClose}
    > 
      <div className="profile-modal" onClick={(e) => e.stopPropagation()}>
        {isEditing ? (
          <>
            <img
              src={avatar}
              alt="avatar"
              className="profile-avatar"
              onClick={() => document.getElementById('avatarInput').click()}
              style={{ cursor: 'pointer' }}
            />
            <input
              type="file"
              id="avatarInput"
              accept="image/*"
              onChange={handleAvatarChange}
              style={{ display: 'none' }}
            />
            <input
              type="text"
              value={nickname}
              onChange={(e) => setNickname(e.target.value)}
              className="profile-input"
              placeholder="昵称"
            />
            <select
              value={gender} // 用于显示当前选择的性别
              onChange={(e) => setGender(e.target.value)} // 当用户选择不同的性别时更新 state
              className="profile-input"
              placeholder="性别"
            >
              <option value="男">男</option>
              <option value="女">女</option>
              <option value="未知">未知</option>
            </select>

            <input
              type="text"
              value={signature}
              onChange={(e) => setSignature(e.target.value)}
              className="profile-input"
              placeholder="个性签名"
            />

            <input
              type="date"
              value={birthday}
              onChange={(e) => setBirthday(e.target.value)}
              className="profile-input"
              placeholder="生日"
            />
            <div className="profile-btn-group">
              <button className="profile-btn" onClick={handleSave}>
                保存
              </button>
              <button className="profile-btn" onClick={handleCancel}>
                取消
              </button>
            </div>
          </>
        ) : (
          <>
            <img src={avatar} alt="avatar" className="profile-avatar" />
            <p className="profile-text">昵称：{nickname}</p>
            <p className="profile-text">性别：{gender}</p>
            <p className="profile-text">个性签名：{signature}</p>
            <p className="profile-text">生日：{birthday}</p>
            <button className="profile-btn" onClick={handleEdit}>
              编辑个人信息
            </button>
          </>
        )}
      </div>
    </div>
  );
};

export default ProfileModal;


